import Config from "@/config/index";
import storage from "@/utils/storage"
//官方文档https://wendux.github.io/dist/#/doc/flyio/readme
//#ifdef H5
var Fly = require("flyio/dist/npm/fly")
//#endif

//#ifdef MP-WEIXIN
var Fly = require("flyio/dist/npm/wx")
//#endif
var fly = new Fly


//设置超时
fly.config.timeout = 30000;
//设置请求基地址
fly.config.baseURL = Config.apiUrl // http请求地址

// 添加请求拦截器
fly.interceptors.request.use((request) => {
	// 在发送请求之前做些什么
	//TODO：此根据具体项目具体走。不同api不同，带的head也不同
	let token = storage.get('login_info') || ''
	if (token) {
		request.headers['Content-Type'] = "application/json";
		request.headers['Authorization'] = "Bearer " + token.token
	}
	return request
}, function(error) {
	// 对请求错误做些什么
	return Promise.reject(error)
})

fly.interceptors.response.use((res) => {
	if (res.status === 200) {
		return res.data
	} else {
		console.log('response', res.statusText)
	}
}, (error) => {
	uni.showToast({
		title: "服务器繁忙,请稍后再试...",
		icon: "none",
	})
	if (error.status === 401) {
		wx.navigateTo({
			url: "/pages/auth/index",
		})
	}
	return Promise.reject(error)
})

export default fly
